package com.intramirror.msdemo.client;

import com.netflix.appinfo.MyDataCenterInstanceConfig;
import com.netflix.client.ClientFactory;
import com.netflix.config.ConfigurationManager;
import com.netflix.discovery.DefaultEurekaClientConfig;
import com.netflix.discovery.DiscoveryManager;
import com.netflix.loadbalancer.DynamicServerListLoadBalancer;
import com.netflix.loadbalancer.RoundRobinRule;
import com.netflix.loadbalancer.Server;
import io.github.xdiamond.client.XDiamondConfig;

import java.util.Properties;

/**
 * 项目启动时需要通过-D指定以下参数
 * xdiamond_server：xdiamond的server地址
 * xdiamond_secret_key：xdiamond中对应环境的secretKey
 * xdiamond_env：环境变量，默认为dev
 * <p>
 * 使用时请根据自己的需求更改XDiamondConfig的GroupId和ArtifactId
 */
public class SearchAddressSelector {

    private static RoundRobinRule chooseRule = new RoundRobinRule();

    static {
        // 加载ribbon配置文件
        XDiamondConfig config = new XDiamondConfig();
        config.setServerHost(System.getProperty("xdiamond_server"));
        config.setServerPort(5678);
        config.setGroupId("com.intramirror.search");
        config.setArtifactId("search");
        config.setVersion("1.0.0");
        config.setProfile(System.getProperty("xdiamond_env","dev"));
        config.setSecretKey(System.getProperty("xdiamond_secret_key","o4rzl92668k"));
        config.init();
        Properties properties = config.getProperties();
        properties.setProperty("search.ribbon.NIWSServerListClassName", "com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList");
        properties.setProperty("eureka.registration.enabled", "false");
        properties.setProperty("eureka.preferSameZone", "true");
        properties.setProperty("eureka.shouldUseDns", "false");
        properties.setProperty("eureka.decoderName", "JacksonJson");

        ConfigurationManager.loadProperties(properties);
        // 初始化Eureka Client
        DiscoveryManager.getInstance().initComponent(new MyDataCenterInstanceConfig(), new DefaultEurekaClientConfig());
    }

    public static ServiceAddress selectOne(String clientName) {
        DynamicServerListLoadBalancer lb = (DynamicServerListLoadBalancer) ClientFactory.getNamedLoadBalancer(clientName);
        Server selected = chooseRule.choose(lb, null);
        if (null == selected) {
            return null;
        }
        return new ServiceAddress(selected.getHost(), selected.getPort());
    }
}
